#!/usr/bin/python
# -*- coding: utf-8 -*-

import MySQLdb
from MySQLdb.cursors import DictCursor
from igor import logging
from igor import const 
from utils.model import singleton

@singleton
class DBUtils:
   
    def connect(self):
        #const.mysqldb.update({'charset': 'utf8'})
        #conn = MySQLdb.connect(**const.mysqldb)
        conn = MySQLdb.connect(host='localhost', user='ssj', passwd='ssjpasswd',
               db = 'shg', port = 3306, charset = 'utf8')
        return conn

    def close(self, conn, cur):
        try:
            if cur:
                cur.close()
            if conn:
                conn.close()
        except MySQLdb.Error, err:
            logging.log(err) 


    def execute_dict(self, sql, params=()):
        ret, conn, cur = None, None, None
        try:
            conn = self.connect()
            cur = conn.cursor(DictCursor)
            cur.execute('SET AUTOCOMMIT=0')
            cur.execute('SET NAMES utf8')
            cur.execute(sql, params)
            conn.commit()
            ret = cur.fetchall()
        except MySQLdb.Error, err:
            logging.log(err)
        finally:
            self.close(conn, cur)
        return ret 

    def execute(self, sql, params=()):
        ret, conn, cur = None, None, None
        try:
            conn = self.connect()
            cur = conn.cursor()
            cur.execute('SET AUTOCOMMIT=0')
            cur.execute('SET NAMES utf8')
            cur.execute(sql, params)
            conn.commit()
            ret = cur.fetchall()
        except MySQLdb.Error, err:
            logging.log(err)
        finally:
            self.close(conn, cur)
        return ret 



        
